package com.imooc.coupon.advice;

import com.imooc.coupon.annotation.IgnoreResonseAdvice;
import com.imooc.coupon.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 *
 */
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice {
    /*
    判断是否需要对响应进行处理 是：需要，否：不需要
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //如果当前类标识了@IgnoreResponseAvide注解。则不需要处理
        if(methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResonseAdvice.class)){
            return false;
        }
        //如果当前方法标识了@IgnoreResponseAvide注解。则不需要处理
        if(methodParameter.getMethod().isAnnotationPresent(IgnoreResonseAdvice.class)){
            return false;
        }
        return true   ;
    }

    /**
     * 响应返回之前的处理
     * @param o
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //定义最终的返回对象
        CommonResponse<Object> response = new CommonResponse();
        //如果O是null.response 不需要设置data,
        if(null == o){
            return response;
        }else if(o instanceof CommonResponse){
            return (CommonResponse)o;
        }else{
            response.setData(o);
        }
        return null;
    }
}
